<template>
  <div ref="wrapper">
    <slot />
  </div>
</template>

<script>
import BScroll from 'better-scroll'
export default {
  name: 'scroll',
  props: {
    probeType: {
      type: Number,
      default: 1
    },
    click: {
      type: Boolean,
      default: true
    },
    scrollX: {
      type: Boolean,
      default: false
    },
    scrollY: {
      type: Boolean ,
      default: false
    },
    // 是否派发滚动事件
    listenScroll: {
      type: Boolean,
      default: false
    },
    // 派发滚动到底部事件
    pullup: {
      type: Boolean,
      default: false
    },
    // 列表数据
    data: {
      type: Array,
      default: null
    }
  },
  data () {
    return {
      scroll: null
    }
  },
  mounted () {
    this.$nextTick(() => {

      this._initScroll()
    })
  },
  methods: {
    _initScroll () {
      if (!this.$refs.wrapper) {
        return
      }
      this.scroll = new BScroll(this.$refs.wrapper, {
        probeType: this.probeType,
        click: this.click,
        scrollX: this.scrollX,
        scrollY: this.scrollY
      })
      // 是否派发滚动事件
      if (this.listenScroll) {
        this.scroll.on('scroll', pos => this.$emit('scroll', pos))
      }
      // 是否派发滚动到底部事件
      if (this.pullup) {
        this.scroll.on('scrollEnd', () => {
          if (this.scroll.y <= (this.scroll.maxScrollY + 50)) {
            this.$emit('scrollToEnd')
          }
        })
      }
    },
    refresh () {
      this.scroll && this.scroll.refresh()
    },
    scrollTo (x, y, time=300) {
      // 代理better-scroll的scrollTo方法
      this.scroll && this.scroll.scrollTo(x,y,time)
    },
    scrollToElement(el, time =10) {
      // 代理better-scroll的scrollToElement方法
      this.scroll && this.scroll.scrollToElement(el, time)
    }
  },
  watch: {
     // 监听数据的变化，延时refreshDelay时间后调用refresh方法重新计算，保证滚动效果正常
    data () {
      setTimeout(() => {
        this.refresh()
      }, 20)
    },
  }
}

</script>
<style lang='scss' scoped>

</style>
